<template>
  <h1>食物热量查询</h1>
  <div class="food-page">
    <div class="search-container">
      <input 
        type="text" 
        v-model="searchKey" 
        placeholder="搜索食物名称/分类（如：苹果、肉类）"
        class="search-input"
      >
      <button @click="filterFoods" class="search-btn">
        <i class="fa fa-search"></i> 搜索
      </button>
    </div>
    
    <!-- 新增分类筛选按钮 -->
    <div class="category-buttons">
      <button 
        v-for="category in categories" 
        :key="category" 
        :class="['category-btn', activeCategory === category ? 'active' : '']"
        @click="filterByCategory(category)"
      >
        {{ category }}
      </button>
      <button 
        class="category-btn reset-btn"
        :class="{ active: !activeCategory }"
        @click="resetCategory"
      >
        全部
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <i class="fa fa-spinner fa-spin"></i> 正在加载食物数据...
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">
      <i class="fa fa-exclamation-circle"></i> {{ error }}
    </div>

    <!-- 横向卡片列表 -->
    <div v-else class="food-grid">
      <div 
        v-for="(item, index) in filteredFoodData" 
        :key="item.food_id" 
        class="food-card"
        @click="goToDetail(item.food_id)"
      >
        <div class="card-content">
          <h3>{{ item.name }}</h3>
          <div class="calories">
            <span class="value">{{ item.calories }}</span> kcal
          </div>
          <!-- 分类标签 -->
          <div class="category-badge" :class="`badge-${getCategoryColor(item.food_category)}`">
            {{ item.food_category }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const foodData = ref([]);
const searchKey = ref('');
const loading = ref(true);
const error = ref(null);
const activeCategory = ref(''); // 新增：当前选中的分类

// 分类列表
const categories = ref(['水果', '肉类', '主食', '蔬菜']);

// 计算属性实现搜索过滤（支持名称、分类搜索和分类按钮筛选）
const filteredFoodData = computed(() => {
  // 先按分类筛选
  let filteredByCategory = activeCategory.value 
    ? foodData.value.filter(item => item.food_category === activeCategory.value)
    : foodData.value;
  
  // 再按搜索关键词筛选
  if (searchKey.value.trim()) {
    const keyword = searchKey.value.toLowerCase();
    filteredByCategory = filteredByCategory.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.food_category.toLowerCase().includes(keyword)
    );
  }
  
  return filteredByCategory;
});

// 获取食物列表数据
onMounted(async () => {
  try {
    const response = await axios.get('http://localhost:8080/MDMS0214_war/food/all');
    foodData.value = response.data;
  } catch (err) {
    error.value = '抱歉，暂时无法获取食物数据，请稍后重试';
    console.error('食物数据加载失败:', err);
  } finally {
    loading.value = false;
  }
});

// 跳转详情页
const goToDetail = (id) => {
  router.push({ name: 'FoodDetailVue', params: { id } });
};

// 根据分类返回不同颜色
const getCategoryColor = (category) => {
  const colors = {
    '水果': 'primary',
    '蔬菜': 'success',
    '主食': 'warning',
    '肉类': 'danger',
    '其他': 'secondary'
  };
  return colors[category] || 'primary';
};

// 新增：按分类筛选
const filterByCategory = (category) => {
  activeCategory.value = category;
  searchKey.value = ''; // 清空搜索框
};

// 新增：重置分类筛选
const resetCategory = () => {
  activeCategory.value = '';
  searchKey.value = ''; // 清空搜索框
};
</script>

<style scoped>
.food-page {
  font-family: 'Segoe UI', sans-serif;
  background: url('your-bg-image-url.jpg') no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  padding: 20px;
  min-height: 100vh;
}

.search-container {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  font-size: 14px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.search-btn {
  padding: 12px 24px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 24px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background-color: #45a049;
}

/* 新增：分类按钮样式 */
.category-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 24px;
  justify-content: center;
}

.category-btn {
  padding: 8px 16px;
  border: 2px solid #ddd;
  border-radius: 24px;
  background-color: white;
  color: #333;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.category-btn:hover {
  border-color: #4CAF50;
  color: #4CAF50;
}

.category-btn.active {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.reset-btn {
  margin-left: 10px;
}

.food-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 20px;
  border-radius: 8px;
}

.food-card {
  background-color: white;
  border: none;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  height: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  transition: transform 0.2s;
  border-radius: 8px;
}

.food-card:hover {
  transform: translateY(-4px);
}

.card-content {
  padding: 24px;
  width: 100%;
}

.card-content h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.calories {
  font-size: 32px;
  font-weight: 600;
  color: #4CAF50;
}

.calories .value {
  display: block;
  font-size: 48px;
  line-height: 1;
}

/* 分类标签样式 */
.category-badge {
  display: inline-block;
  padding: 4px 12px;
  margin-top: 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
}

.badge-primary { background-color: #e3f2fd; color: #0d47a1; }
.badge-success { background-color: #e8f5e9; color: #1b5e20; }
.badge-warning { background-color: #fff3e0; color: #e65100; }
.badge-danger { background-color: #ffebee; color: #b71c1c; }
.badge-secondary { background-color: #f5f5f5; color: #424242; }

/* 响应式断点 */
@media (max-width: 992px) {
  .food-grid {
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .food-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .card-content h3 {
    font-size: 14px;
  }

  .calories {
    font-size: 28px;
  }

  .calories .value {
    font-size: 40px;
  }
  
  /* 调整分类按钮在小屏幕上的样式 */
  .category-btn {
    padding: 6px 12px;
    font-size: 14px;
  }
}

.loading, .error {
  padding: 40px 20px;
  text-align: center;
  line-height: 1.6;
}

.error {
  color: #dc3545;
}

h1 {
  text-shadow: 0 0 5px white;
  text-align: center;
  margin-bottom: 30px;
}
</style>